<?php


/**
 * LoginForm class.
 * LoginForm is the data structure for keeping
 * user login form data. It is used by the 'login' action of 'SiteController'.
 */
class InformationForm extends CFormModel {
	public $password;
	public $email;
	public $first_name;
	public $last_name;
	public $phone_number;
	public $initials;
	public $language;

	public function __construct() {
		$record = Yii::app()->user->getState('dbuser');
		if ($record != null) {
			$this->email = $record->email;
			$this->language = $record->language;
			$this->first_name = $record->first_name;
			$this->last_name = $record->last_name;
			$this->phone_number = $record->phone_number;
			$this->initials = $record->initials;
		}
	}

	/**
	 * Declares the validation rules.
	 * The rules state that username and password are required,
	 * and password needs to be authenticated.
	 */
	public function rules() {
		return array (
			array ('email, language, first_name, password, initials', 'required'),
			array ('email', 'email'),
		);
	}

	/**
	 * Declares attribute labels.
	 */
	public function attributeLabels() {
		return array (
			'password' => Yii::t('userinfo', 'Type your current password to apply changes'),
			'email' => Yii::t('userinfo', 'Email address'),
			'language' => Yii::t('languages', 'Language'),
			'email' => Yii::t('user', 'Mail address'),
			'roles' => Yii::t('user', 'Roles'),
			'first_name' => Yii::t('user', 'First Name'),
			'last_name' => Yii::t('user', 'Last Name'),
			'phone_number' => Yii::t('user', 'Phone Number'),
			'initials' => Yii::t('user', 'Initials')
		);
	}

	public function save() {
		if (!$this->hasErrors()) // we only want to authenticate when no input errors
		{
			$identity = new UserIdentity(Yii::app()->user->id, $this->password);
			$identity->authenticate();
			switch ($identity->errorCode) {
				case UserIdentity::ERROR_NONE :
					// Changing mail address
					$identity->getUser()->email = $this->email;
					$identity->getUser()->language = $this->language;
					Yii::app()->setLanguage($this->language);
					$identity->getUser()->first_name = $this->first_name;
					$identity->getUser()->last_name = $this->last_name;
					$identity->getUser()->phone_number = $this->phone_number;
					$identity->getUser()->initials = $this->initials;
					if (!$identity->getUser()->save())
					{
						$this->addErrors($identity->getUser()->getErrors());
					}
					Yii::app()->user->setState('dbuser', $identity->getUser());
					break;
				case UserIdentity::ERROR_USERNAME_INVALID :
					Yii::app()->user->logout();
					$this->redirect(Yii::app()->homeUrl);
					break;
				default : // UserIdentity::ERROR_PASSWORD_INVALID
					$this->addError('password', Yii::t('userinfo', 'Current password is incorrect.'));
					break;
			}
		}
		
		return !$this->hasErrors();
	}
}

